<template>
  <!-- 绿色提示条 - 仅在第三步显示 -->
  <div v-if="currentStep === 2 && !isBannerClosed" class="success-banner">
    <div class="banner-content">
      <span class="banner-text">メールアドレス確認が行われました。あとしばらくで会員登録が完了します。</span>
      <button class="banner-close" @click="closeBanner">×</button>
    </div>
  </div>
  
  <div class="register-container">
    <div class="register-content">
      <div class="register-right" v-if="currentStep === 0">
        <div class="register-images">
          <img src="/reg/join_us.png" alt="加入我们" class="join-us-image">
          <div class="japanese-text">さあ、クラウドワークスをはじめよう。</div>
          <img src="/reg/regimg.png" alt="注册页面图片" class="register-image">
        </div>
      </div>

      <div class="register-left">
          <EmailStep 
            v-if="currentStep === 0" 
            v-model="emailForm" 
            @next="goToNextStep"
            @update:modelValue="handleEmailFormUpdate"
          />
      </div>
                <!-- 第二步：邮件已发送提示 -->
          <!-- <EmailSentStep 
            v-if="currentStep === 1" 
            :email="emailForm.email"
            :is-email-sending="isEmailSending"
            :is-sending-code="isSendingCode"
            :countdown="countdown"
            @continue="goToFinalStep"
            @change-email="backToFirstStep"
            @resend-code="resendVerificationCode"
            style="position: absolute;right: 100px;"

          /> -->
          <!-- 第三步：完善资料 -->
          <!-- <RegisterFormStep 
            v-if="currentStep === 2" 
            :email="emailForm.email"
            v-model="registerForm"
            @submit="submitRegistration"
            @change-email="backToFirstStep"
           
          /> -->


    </div>
    
  </div>
  <div class="footdt">
    <div>
      <span>利用規約</span>
      <span>|</span>
      <span>特定商取引法に基づく表記</span>
      <span>|</span>
      <span><a href="/article/3">個人情報保護方針</a></span>
    </div>
    <div class="copyright">
      copyright (c) WorkMatch all rights reserved.
    </div>
  </div>
  <CustomerService />

</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '../api/index'
import { useRouter } from 'vue-router'
import CustomerService from '../components/CustomerService.vue'
import EmailStep from '../components/EmailStep.vue'
import EmailSentStep from '../components/EmailSentStep.vue'
import RegisterFormStep from '../components/RegisterFormStep.vue'

// 初始化路由
const router = useRouter()

// 当前步骤
const currentStep = ref(0)

// 绿色条关闭状态
const isBannerClosed = ref(false)

// 关闭绿色条
const closeBanner = () => {
  isBannerClosed.value = true
}

// 邮箱表单
const emailForm = reactive({
  email: localStorage.getItem('registerEmail') || '',
  verificationCode: ''
})

// 如果从首页传递了邮箱，自动进入第二步
onMounted(() => {
  const registerEmail = localStorage.getItem('registerEmail')
  if (registerEmail) {
    emailForm.email = registerEmail
    console.log('从localStorage获取的email:', registerEmail)
    console.log('设置后的emailForm:', emailForm)
    // 自动发送验证码
    goToNextStep()
  }
})

// 注册表单
const registerForm = reactive({
  verificationCode: '',
  username: '',
  password: '',
  repassword: '',
  type: 1, // 默认为个人
  surname: '',
  name: '',
  surname2: '',
  name2: '',
  address: '',
  zip_code: '',
  prefectures: '',
  company_name: '',
  company_number: '',
  company_phone: '',
  agreeTerms: false
})

// 验证码按钮状态
const isSendingCode = ref(false)
const countdown = ref(0)
const codeButtonText = ref('重新发送')
// 邮件发送状态
const isEmailSending = ref(false)

// 处理EmailStep组件的数据更新
const handleEmailFormUpdate = (newValue) => {
  console.log('handleEmailFormUpdate - 接收到的数据:', newValue)
  if (newValue && newValue.email !== undefined) {
    emailForm.email = newValue.email
    emailForm.verificationCode = newValue.verificationCode || ''
    console.log('handleEmailFormUpdate - 更新后的emailForm:', emailForm)
  }
}

// 进入第二步（发送验证码并显示邮件已发送提示）
const goToNextStep = () => {
  console.log('goToNextStep - 当前emailForm:', emailForm)
  console.log('goToNextStep - emailForm.email:', emailForm.email)
  
  // 确保email不为空再发送验证码
  if (!emailForm.email) {
    ElMessage.error('メールアドレスが入力されていません')
    return
  }
  
  // 发送验证码
  sendVerificationCode()
  // 跳转到邮件发送页面
  router.push({
    path: '/email-sent',
    query: { email: emailForm.email }
  })
}

// 进入第三步（资料填写）
const goToFinalStep = () => {
  // 跳转到注册表单页面，传递邮箱参数
  router.push({
    path: '/register-form',
    query: { email: emailForm.email }
  })
}

// 发送验证码
const sendVerificationCode = () => {
  console.log('发送验证码时的emailForm:', emailForm)
  console.log('发送验证码时的email值:', emailForm.email)
  
  if (!emailForm.email) {
    ElMessage.error('メールアドレスが入力されていません')
    return
  }
  
  isSendingCode.value = true
  isEmailSending.value = true // 设置邮件发送中状态
  countdown.value = 60
  codeButtonText.value = `${countdown.value}秒後に再試行`
  
  // 调用后端API发送验证码
   userApi.sendCode(emailForm.email).then(res => {
    console.log('API响应:', res)
    console.log('当前emailForm:', emailForm)

    // 检查返回的状态码
    if (res.code === 1) {
      // 验证码发送成功，显示后端返回的消息
      // ElMessage.success('メールアドレスの送信に成功しました')
      isEmailSending.value = false // 设置邮件发送完成状态
      const timer = setInterval(() => {
        countdown.value--
        codeButtonText.value = `${countdown.value}秒后重试`
        if (countdown.value <= 0) {
          clearInterval(timer)
          isSendingCode.value = false
          codeButtonText.value = '重新发送'
        }
      }, 1000)
    } else {
      // 验证码发送失败，显示后端返回的错误消息
      ElMessage.error('メールアドレスの送信に失敗しました')
      isSendingCode.value = false
      isEmailSending.value = false // 设置邮件发送完成状态
      codeButtonText.value = 'メールアドレスを再送信'
    }
  }).catch(error => {
    ElMessage.error('メールアドレスの送信に失敗しました')
    isSendingCode.value = false
    isEmailSending.value = false // 设置邮件发送完成状态
    codeButtonText.value = 'メールアドレスを再送信'
  })
}

// 重新发送验证码
const resendVerificationCode = () => {
  if (!isSendingCode.value) {
    sendVerificationCode()
    // 移除这里的消息提示，因为 sendVerificationCode 函数中已经根据后端返回处理了消息提示
  }
}

// 返回第一步
const backToFirstStep = () => {
  // 跳转回注册页面
  router.push('/register')
}

// 提交注册
const submitRegistration = (formData) => {
  // 构建注册数据
  const registrationData = {
    code: formData.verificationCode,
    username: formData.username,
    password: formData.password,
    repassword: formData.repassword,
    email: emailForm.email,
    type: formData.type,
    surname: formData.surname,
    name: formData.name,
    surname2: formData.surname2,
    name2: formData.name2,
    address: formData.address,
    zip_code: formData.zip_code,
    prefectures: formData.prefectures,
    company_name: formData.company_name,
    company_number: formData.company_number,
    company_phone: formData.company_phone
  }
  // 调用后端API进行注册
  userApi.register(registrationData).then(res => {
    ElMessage.success('登録が成功しました！')
    // 注册成功后跳转到登录页
    router.push('/login')
  }).catch(error => {
    ElMessage.error( '登録に失敗しました。後でもう一度お試しください。')
  })
}
</script>

<style scoped>
/* 绿色成功提示条样式 */
.success-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: #d4edda;
  border-bottom: 1px solid #c3e6cb;
  padding: 12px 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.banner-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  position: relative;
}

.banner-icon {
  color: #155724;
  font-weight: bold;
  margin-right: 8px;
  font-size: 16px;
}

.banner-text {
  color: #155724;
  font-size: 14px;
  font-weight: 500;
}

.banner-close {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #155724;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.banner-close:hover {
  background-color: rgba(21, 87, 36, 0.1);
}

/* 当显示绿色条时，调整容器的上边距 */
.register-container {
  margin-top: 0;
}

/* *{
    margin: 0;
  padding: 0;
  box-sizing: border-box;

} */
/* .box1{
  position: relative;
  top: 10px;
} */
.register-container {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  width: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e7f1fa;
  padding-bottom: 60px; /* 为底部元素留出空间 */
  padding-top: 50px; /* 为绿色条留出空间 */
}

.footdt {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 14px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px 0;
  background-color: #e7f1fa;
}

.footdt .copyright {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.footdt span {
  margin: 0 5px;
}

.register-content {
  display: flex;
  width: 100%;
  max-width: 1000px;
  flex-direction: row-reverse;
  border-radius: 8px;
  /* box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); */
  overflow: hidden;
}

.register-left {
position: absolute;
top: 10px;
left: 100px;
  flex: 1;
  /* padding: 30px; */
  display: flex;
  flex-direction: column;
  background-color: transparent;
}

/* 当右侧不显示时，左侧占据全宽 */
.register-content .register-left {
  transition: all 0.3s ease;
}

.register-content .register-left:only-child,
.register-content .register-left:nth-last-child(1):first-child {
  flex: 1 1 100%;
  max-width: 100%;
}

.register-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
}

.register-images {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  background-color: transparent;
}

.register-image {
  position: absolute;
  top: 190px;
  right: 10px;
  max-width: 70%;
  max-height: 70%;
  object-fit: contain;
  /* margin-top: 20px; */
}

.join-us-image {
  position: absolute;
  top: 100px;
    left: 900px;
  object-fit: contain;
  height: 90px;
  margin-bottom: 40px;
}

.register-box {
  width: 100%;
  max-width: auto;
  margin: 0 auto;
  background-color: white;
  padding: 30px;
  border-radius: 8px;
}

/* 当处于第二步或第三步时，注册框样式调整 */
.register-left:only-child .register-box,
.register-left:nth-last-child(1):first-child .register-box {
  max-width: 720px;
}

.logo-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.logo-container a {
  display: inline-block;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.logo-container a:hover {
  transform: scale(1.05);
}

.logo {
  height: 60px;
  object-fit: contain;
}

.register-title {
  text-align: center;
  margin-bottom: 15px;
  color: #333;
}

.register-button {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  height: 40px;
  margin-top: 15px;
}

.register-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  flex-wrap: wrap;
}

.login-link {
  color: var(--el-color-primary);
  text-decoration: none;
  margin-left: auto;
  margin-top: 15px;
}

.terms-link {
  color: var(--el-color-primary);
  text-decoration: none;
}

/* 移动端响应式布局 - 最优化版本 */
@media (max-width: 768px) {
  .register-container {
    padding: 15px;
    min-height: 100vh;
    align-items: flex-start;
    padding-top: 30px;
    padding-bottom: 80px;
  }

  .register-content {
    flex-direction: column;
    max-width: 100%;
    margin: 0;
    width: 100%;
    justify-content: flex-start;
  }

  .register-right {
    display: none;
    /* 在小屏幕上隐藏图片 */
  }

  .register-left {
    position: static;
    width: 100%;
    top: auto;
    left: auto;
    padding: 0;
    max-width: 100%;
    display: flex;
    justify-content: center;
  }

  .footdt {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    margin-top: 0;
    padding: 12px 15px;
    background-color: #e7f1fa;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    font-size: 12px;
    z-index: 1000;
  }

  .footdt .copyright {
    font-size: 10px;
    margin-top: 3px;
  }

  .japanese-text {
    display: none;
  }

  /* 移动端步骤样式调整 */
  .register-left .register-box {
    max-width: 100%;
    width: 100%;
    padding: 25px 20px;
    margin: 0;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    background-color: #ffffff;
  }

  /* 移动端表单元素优化 */
  .register-left :deep(.el-input) {
    margin-bottom: 15px;
  }

  .register-left :deep(.el-input__wrapper) {
    padding: 12px 15px;
    border-radius: 8px;
    font-size: 16px;
  }

  .register-left :deep(.el-button) {
    height: 48px;
    font-size: 16px;
    border-radius: 8px;
    font-weight: 500;
  }

  .register-left :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  .register-left :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    line-height: 1.4;
  }

  .register-left :deep(.el-radio-group) {
    display: flex;
    justify-content: space-around;
    margin: 10px 0;
  }

  .register-left :deep(.el-radio) {
    margin-right: 0;
    flex: 1;
    text-align: center;
  }

  .register-left :deep(.el-checkbox) {
    line-height: 1.5;
  }

  .register-left :deep(.el-checkbox__label) {
    font-size: 13px;
    line-height: 1.4;
  }
}

/* 日文文本样式 */
.japanese-text {
  position: absolute;
  top: 200px;
  left: 300px;

  font-size: 1.2rem;
  font-weight: 500;
  color: #333;
  margin: 15px 0;
  text-align: center;
  width: 100%;
  font-family: 'Noto Sans JP', sans-serif;
  letter-spacing: 0.05em;
  line-height: 1.5;
}





/* 小屏幕手机端优化 */
@media (max-width: 480px) {
  .register-container {
    padding: 10px;
    padding-top: 20px;
    padding-bottom: 90px;
  }

  .register-left {
    padding: 0;
  }

  .register-left .register-box {
    padding: 20px 15px;
    border-radius: 8px;
    margin: 0 5px;
  }

  .footdt {
    font-size: 11px;
    padding: 10px 10px;
    text-align: center;
  }

  .footdt span {
    margin: 0 3px;
    display: inline-block;
  }

  .footdt .copyright {
    font-size: 9px;
    margin-top: 4px;
  }

  /* 超小屏幕表单优化 */
  .register-left :deep(.el-input__wrapper) {
    padding: 10px 12px;
    font-size: 15px;
  }

  .register-left :deep(.el-button) {
    height: 44px;
    font-size: 15px;
  }

  .register-left :deep(.el-form-item__label) {
    font-size: 13px;
  }

  .register-left :deep(.el-checkbox__label) {
    font-size: 12px;
  }

  .register-left :deep(.el-radio__label) {
    font-size: 13px;
  }
}

/* 平板端优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .register-container {
    padding: 20px;
    padding-bottom: 80px;
  }

  .register-left {
    position: static;
    top: auto;
    left: auto;
    margin: 0 auto;
    max-width: 650px;
    display: flex;
    justify-content: center;
  }

  .register-images {
    flex-direction: column;
    align-items: center;
  }

  .register-image {
    max-width: 80%;
    margin-bottom: 20px;
    position: static;
  }

  .join-us-image {
    margin-left: 0;
    margin-top: 20px;
    position: static;
    height: 80px;
  }

  .japanese-text {
    position: static;
    margin: 20px 0;
    font-size: 1.1rem;
  }

  .register-left .register-box {
    max-width: 550px;
    width: 100%;
    padding: 35px 30px;
    border-radius: 10px;
    box-shadow: 0 6px 25px rgba(0, 0, 0, 0.1);
  }

  .footdt {
    position: fixed;
    bottom: 0;
    padding: 15px 20px;
    font-size: 13px;
  }

  /* 平板端表单优化 */
  .register-left :deep(.el-input__wrapper) {
    padding: 12px 16px;
    font-size: 15px;
  }

  .register-left :deep(.el-button) {
    height: 46px;
    font-size: 15px;
  }

  .register-left :deep(.el-form-item__label) {
    font-size: 14px;
  }
}
</style>